import urlParser from './urlParser.js';
const getRealTitle = (text) => {
    // don't try to parse URL's
    if (urlParser.isURL(text)) {
      return text;
    }

    var possibleCharacters = ['|', ':', ' - ', ' — '];

    for (var i = 0; i < possibleCharacters.length; i++) {
      var char = possibleCharacters[i];
      // match url's of pattern: title | website name
      var titleChunks = text.split(char);

      if (titleChunks.length >= 2) {
        var titleChunksTrimmed = titleChunks.map((c) => c.trim());
        if (
          titleChunksTrimmed[titleChunksTrimmed.length - 1].length < 5 ||
          titleChunksTrimmed[titleChunksTrimmed.length - 1].length /
            text.length <=
            0.3
        ) {
          return titleChunks.slice(0, -1).join(char);
        }
      }
    }

    // fallback to the regular title

    return text;
};
function parseBookmarkSearch(text) {
  var tags = text
    .split(/\s/g)
    .filter(function (word) {
      return word.startsWith('#') && word.length > 1;
    })
    .map((t) => t.substring(1));

  var newText = text;
  tags.forEach(function (word) {
    newText = newText.replace('#' + word, '');
  });
  newText = newText.trim();
  return {
    tags,
    text: newText,
  };
}
function itemMatchesTags(item, tags) {
  for (var i = 0; i < tags.length; i++) {
    if (!item.tags.filter((t) => t.startsWith(tags[i])).length) {
      return false;
    }
  }
  return true;
}
const debounce = function (fn, delay) {
  var timer = null;
  return function () {
    var context = this;
    var args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
};
export default {getRealTitle, parseBookmarkSearch, itemMatchesTags, debounce };
